//
// Created by 28365 on 2025/3/13.
//

#include "../include/config/proceessing/search/IntelligentSearchProcessor.h"
#include "../include/exception/UnConnectServerException.h"
#include "config/server_api/IUpdaterServer.h"
#include "config/proceessing/record/IUpdateRecorder.h"
#include <nlohmann/json.hpp>
#include <vector>
#include <algorithm> // for std::sort

typedef nlohmann::json json;

void IntelligentSearchProcessor::getUpdateRes(map<int, list<Res>, less<>> &needRes, const ODUpdater &odUpdater,const UpdateRecord &updateRecord) {

    IUpdaterServer *updaterServer = odUpdater.getUpdaterServer();

    ReqValue<vector<int>> reqValue = updaterServer->getVersions(updateRecord.getVersion(),odUpdater.getUnpublishKey(),odUpdater);
    if (reqValue.getServerApiState() != SUCCESS){
        throw UnConnectServerException("无法连接至服务器");
    }

    //当前版本到最新版之间的所有版本号
    vector<int> versions = reqValue.getData();

    if (versions.empty()){
        return;
    }

    //从最新版到旧版排序,确保检索顺序正确
    sort(versions.begin(),versions.end(),greater<>());

    //用于去除不同版本中相同路径的资源，以最新版为基
    set<string> existPath;

    for (const auto &v: versions){
        if (v == updateRecord.getVersion()){
            //与当前版本相同
            continue;
        }

        ReqValue<vector<Res>> versionRes = updaterServer->getVersionRes(v,odUpdater.getLabelId(),odUpdater.getUnpublishKey(),odUpdater);

        if (versionRes.getServerApiState() != SUCCESS){
            throw UnConnectServerException("无法连接至服务器");
        }

        //当检索的版本是记录中的未完成版本时，将取出未完成版本中完成的资源进行对比排除
        set<int64_t> completedRes = updateRecord.getNotCompletedVersion() == v ? updateRecord.getResId() : set<int64_t>();

        list<Res> resList;

        for (const auto &item: versionRes.getData()){
            string path = item.getResPath();
            int64_t id = item.getId();
            if (existPath.find(path) == existPath.end() && completedRes.find(id) == completedRes.end()){
                resList.emplace_back(item);
                existPath.emplace(path);
            }
        }
        if (!resList.empty()){
            needRes.emplace(v,resList);
        }
    }

    if (existPath.empty()){
        IUpdateRecorder *updateRecorder = odUpdater.getUpdateRecorder();
        updateRecorder->useVersion(&odUpdater,versions[0]);
        updateRecorder->complete();
    }
}

IntelligentSearchProcessor::~IntelligentSearchProcessor() = default;
